import { User } from "@/types/system/user";
import QueryForm from "../../user/components/QueryForm";
import { useAuthUser } from "../hooks/useAuthUser";
import AuthUser from "./AuthUser";
import { queryRoleUser, unbindUser } from "@/api/system/role";
import {
  Avatar,
  Button,
  Modal,
  Pagination,
  Space,
  Table,
  TableProps,
} from "antd";
import { useCallback, useEffect, useState } from "react";
import PermissionBtn from "@/components/PermissionBtn";
import { ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";

interface Props {
  roleId: string;
  roleName: string;
}
export default function ViewUserAuth(props: Props) {
  const [loading, setLoading] = useState(false);
  const [searchForm, setSearchForm] = useState<User.Query>({
    userName: "",
    nickName: "",
    email: "",
    phonenumber: "",
    sex: "",
    type: "",
    // 账号状态（0正常 1停用
    status: "",
  });
  const [pagination, setPagination] = useState<Pagination>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  });
  const [tableData, setTableData] = useState<User.Row[]>([]);
  /**
   * 获取用户列表
   */
  const getUserList = useCallback(async () => {
    if (!props.roleId) return;
    const { nickName, email, phonenumber, sex, type, userName, status } =
      searchForm;

    const params = {
      nickName,
      email,
      phonenumber,
      sex,
      type,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      status,
      userName,
      roleId: props.roleId,
    };
    setLoading(true);
    const res = await queryRoleUser(params);
    setLoading(false);
    if (res.code === 200) {
      setTableData(res.data.rows || []);
      setPagination({
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        total: res.data.total || 0,
      });
    }
  }, [pagination.pageNo, pagination.pageSize, props.roleId, searchForm]);
  const { isModalOpen, close, openOptionDialog, roleId, roleName } =
    useAuthUser();
  const removeInf = async (user: User.Row) => {
    const param = {
      roleId: props.roleId,
      userIdList: [user.id],
    };

    const res = await unbindUser(param);
    if (res) {
      if (tableData.length === 1) {
        pagination.pageNo = Math.max(pagination.pageNo - 1, 1);
      }
      getUserList();
    }
  };
  useEffect(() => {
    getUserList();
  }, [getUserList]);
  const showConfirm = (row: User.Row) => {
    Modal.confirm({
      title: "警告",
      icon: <ExclamationCircleFilled />,
      content: `确认解绑${row.nickName}?`,
      okText: "确认",
      cancelText: "取消",
      okType: "danger",
      onOk() {
        console.log("OK");
        removeInf(row);
      },
    });
  };
  const columns: TableProps<User.Row>["columns"] = [
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      width: 60,
      align: "center",
      fixed: true,
      render: (_, { avatar }) => (
        <>
          {avatar && (
            <Avatar size={35} src={<img src={avatar} alt="avatar" />} />
          )}
        </>
      ),
    },
    {
      title: "昵称",
      key: "nickName",
      dataIndex: "nickName",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "用户名",
      key: "userName",
      dataIndex: "userName",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "邮箱",
      key: "email",
      dataIndex: "email",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "手机号",
      key: "phonenumber",
      dataIndex: "phonenumber",
      ellipsis: true,
      width: 180,
      align: "center",
    },
    {
      title: "性别",
      key: "sex",
      dataIndex: "sex",
      ellipsis: true,
      width: 180,
      align: "center",
      render: (_, { sex }) => (
        <>{{ 0: "男", 1: "女", 2: "未知" }[String(sex)]}</>
      ),
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 240,
      align: "center",
      render: (_, row) => (
        <Space size={2} wrap>
          <Button
            type="link"
            danger
            onClick={() => {
              showConfirm(row);
            }}
          >
            解绑
          </Button>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <div className="page__wrap--g">
        <div className="form__wrap--g">
          <QueryForm
            onChange={(form: User.Query) => {
              setPagination({
                ...pagination,
                pageNo: 1,
              });
              setSearchForm(form);
            }}
          />
          <PermissionBtn code="role.authUser">
            <Button
              type="primary"
              size="middle"
              icon={<PlusOutlined />}
              onClick={() => {
                openOptionDialog(props.roleId, props.roleName);
              }}
            >
              分配用户
            </Button>
          </PermissionBtn>
        </div>
        <div className="table__wrap--g">
          <Table
            columns={columns}
            dataSource={tableData}
            rowKey="id"
            loading={loading}
            size="small"
            sticky
            bordered
            scroll={{ x: 1300 }}
            pagination={false}
          />
        </div>
        <div className="pagination__wrap--g">
          <Pagination
            pageSize={pagination.pageSize}
            current={pagination.pageNo}
            total={pagination.total}
            showQuickJumper={true}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              setPagination({
                total: pagination.total,
                pageNo: page,
                pageSize: size,
              });
            }}
          />
        </div>
      </div>
      {
        <AuthUser
          isModalOpen={isModalOpen}
          close={close}
          roleId={roleId}
          roleName={roleName}
          change={() => {
            getUserList();
          }}
        />
      }
    </div>
  );
}
